package com.lagou.edu.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Controller
@RequestMapping("model")
public class ModelController {

    /**
     * 局部生效
     */
    @ExceptionHandler(ArithmeticException.class)
    public ModelAndView handleException(ArithmeticException exception, HttpServletResponse response) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("msg", "局部: "+exception.getMessage());
        modelAndView.setViewName("error");
        return modelAndView;
    }

    @RequestMapping("error")
    public ModelAndView error(){
        Date date = new Date();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("date", date);
        modelAndView.setViewName("success");
        int i = 1/0;
        return modelAndView;
    }

    /**
     * SpringMVC 重定向时参数传递的问题
     * 转发：url不会变,参数也不会丢失,⼀个请求
     * 重定向：url会变,参数会丢失需要重新携带参数,两个请求
     */
    @RequestMapping("/redirect")
    public String handleRedirect(String name, RedirectAttributes redirectAttributes) {
        // 方式1: 拼接参数安全性、参数⻓度都有局限
        //return "redirect:handle?name="+name;
        // 方式2: addFlashAttribute⽅法设置了⼀个flash类型属性，该属性会被暂存到session中，在跳转到⻚⾯之后该属性销毁
        // 需要@ModelAttribute("name")
        redirectAttributes.addFlashAttribute("name",name);
        return "redirect:handle";
    }

    @RequestMapping(value = "/handle")
    public ModelAndView handlePost(@ModelAttribute("name") String name) {
        Date date = new Date();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("date",date  + " name ==>>" + name);
        modelAndView.setViewName("success");
        return modelAndView;
    }
}
